import { IArticleItemDetail } from "@/utils/type";
import { Modal, message } from 'antd';
import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";
import styles from './index.less';
import QRCode from 'qrcode';
import { genePoster } from "@/services";

interface IProps {
  detail: IArticleItemDetail
}
const Share: React.FC<IProps> = props => {
  const poster = useRef(null);
  function downlaodPoster() {
    try{
      genePoster({
        name: props.detail.title,
        pageUrl: `/article/${props.detail.id}`,
        html: (poster.current as unknown as HTMLElement).innerHTML,
        width: (poster.current as unknown as HTMLElement).offsetWidth,
        height: (poster.current as unknown as HTMLElement).offsetHeight
      }).then(res=>{
        console.log('res...', res);
        if (res.data.url){
          /**
           * 直接跳转就会下载
           * response header
           *   Content-Disposition: attachment (附件)
           * */
          (window as any)._hmt.push(['_trackEvent', '文章详情', '海报', '海报生成成功']);
          window.location.href = res.data.url;
        }
      })
    }catch{
      (window as any)._hmt.push(['_trackEvent', '文章详情', '海报', '海报生失败']);
      message.error('生成海报失败，请手动截图')
    }
  }
  function closeModal() {
    (window as any)._hmt.push(['_trackEvent', '文章详情', '海报', '关闭海报弹窗']);
    ReactDOM.unmountComponentAtNode(document.querySelector('.shareDialog') as Element)
  }

  const [qr, setQr] = useState('');
  useEffect(() => {
    const host = process.env.NODE_ENV === 'development' ? 'https://creation.shbwyz.com/': 'https://creation.shbwyz.com/';
    if (props.detail.id){
      QRCode.toString(`${host}article/${props.detail.id}`, {type: 'svg'}).then(url=>{
        console.log('url...', url);
        setQr(url);
      })
    }
    (window as any)._hmt.push(['_trackEvent', '文章详情', '海报', '海报生成']);
  }, [props.detail.id]);


  return <Modal className={styles.shareModal} title="分享海报" okText="下载" visible={true} onOk={downlaodPoster} onCancel={closeModal}>
    <div ref={poster}>
      <img src={props.detail.cover} alt="" />
      <p>{props.detail.title}</p>
      <p>{props.detail.summary}</p>
      <div>
        {/* <img src={qr} alt="" /> */}
        <div dangerouslySetInnerHTML={{__html: qr}}></div>
        <div>
          <p>识别二维码查看文章</p>
          <p>原文分享至
            <span>八维创作平台</span>
          </p>
        </div>
      </div>
    </div>
  </Modal>
}
export default Share;

export function share(artilceDetail: IArticleItemDetail) {
  let container = document.querySelector('.shareDialog');
  if (!container) {
    container = document.createElement('div');
    container.className = 'shareDialog';
    document.body.appendChild(container);
  }

  console.log('container...', container);

  ReactDOM.render(<Share detail={artilceDetail} ></Share>, container)
}
